package com.sykj.realm;

import com.sykj.pojo.User;
import com.sykj.servies.LoginServies;
import com.sykj.servies.PermissionServies;
import com.sykj.servies.RoleServies;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    LoginServies loginServies;

    //获取角色
    @Autowired
    RoleServies roleServies;

    @Autowired
    PermissionServies permissionServies;
    //获取指定角色的权限

    //权限验证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //能进入到这里，表示账号已经通过验证了
        String userName =(String) principals.getPrimaryPrincipal();
        //通过service获取角色和权限
        Set<String> roles = roleServies.listRoleNames(userName);
        Set<String> permissions = permissionServies.listPermissions(userName);


        //授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        s.setStringPermissions(permissions);
        System.out.println("Roles ==" + roles);
        //添加角色信息
        s.setRoles(roles);
        return s;

    }


    //登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String userName= token.getPrincipal().toString();
        //获取数据库中的密码
        User user =loginServies.getByname(userName);
        System.out.println("用户:"+user);
        String password = user.getPassword();

        /**
         *   //将用户名进行盐值加密
         * ByteSource.Util.bytes(user.getName())
         */
        //String salt = //user.getSalt();
        //盐放进去
        //这样通过spirng-shiro.xml里配置的 HashedCredentialsMatcher 进行自动校验
        //认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :AdminDatabaseRealm
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,password,ByteSource.Util.bytes(user.getName()),getName());
        return info;
    }
}
